<template>
  <div class="query-page">
    <van-form @submit="handleSearch">
      <van-cell-group inset>
        <van-field v-model="searchForm.orderNo" label="订单号" placeholder="请输入订单号" />
        <van-field v-model="searchForm.billDateRange" label="单据日期" placeholder="选择日期范围"
          @click="showDateRangePicker = true" />
        <!--<van-field
          v-model="searchForm.statusText"
          label="单据状态"
          is-link
          readonly
          placeholder="请选择状态"
          @click="showStatusPicker = true"
        />-->
        <van-button block type="primary" native-type="submit">
          查询
        </van-button>
      </van-cell-group>
    </van-form>

    <van-list v-if="orderList.length">
      <van-cell v-for="(item, index) in orderList" :key="index" :title="`订单号：${item.orderno}`"
        :value="`状态：${statusMap[item.billstatus]}`" @click="showOrderDetail(item)">
        <template #label>
          <div>日期：{{ item.dbilldate }}</div>
          <div>金额：¥{{ item.totalamount }}</div>
        </template>
      </van-cell>
    </van-list>

    <van-empty v-else description="暂无订单数据" />

    <van-calendar type="range" v-model:show="showDateRangePicker" :round="false" position="top"
      @confirm="confirmDateRange" :min-date="new Date(1990,0,1)" @cancel="showDateRangePicker = false" />

    <van-popup v-model:show="showStatusPicker" position="bottom">
      <van-picker :columns="statusOptions" @confirm="confirmStatus" @cancel="showStatusPicker = false" />
    </van-popup>

    <van-popup v-model:show="showDetail" position="bottom" :style="{ height: '80%' }">
      <van-cell-group v-if="currentOrder" inset>
        <van-cell title="订单号" :value="currentOrder.orderno" />
        <van-cell title="单据日期" :value="currentOrder.dbilldate" />
        <van-cell title="状态" :value="statusMap[currentOrder.billstatus]" />

        <van-cell style="background-color: #FF0000;" title="点击下载报告" is-link
          @click="loadpdf(currentOrder.filepk,currentOrder.filename)" />

        <van-cell title="物料明细">
          <template #value>
            <div v-for="(product, idx) in currentOrder.orderitems" :key="idx" class="product-item">
              <div>{{ `${product.matname} (${product.matcode})` }}</div>
              <div>编码：{{ product.matcode }}</div>
              <div>单价：¥{{ product.price }} 数量：{{ product.num }}</div>
              <div>金额：¥{{ product.amount }}</div>
            </div>
          </template>
        </van-cell>
        <van-cell title="检验结果">
          <template #value>
            <div v-for="(jyitem, idx) in currentOrder.jyitems" :key="idx" class="product-item">
              <div>{{ `${jyitem.matname} (${jyitem.matcode})` }}</div>
              <div>编码：{{ jyitem.matcode }}</div>
              <div>元素名称：{{ jyitem.vcheckitemname }} </div>
              <div>检验方法：{{ jyitem.vcheckmethod }}</div>
              <div>检测结果：{{ jyitem.analysissymbol }}{{ jyitem.chkresult }}</div>
              <div>分析单位：{{ jyitem.measdocname }}</div>
              <div>检测依据：{{ jyitem.jcyjtext }}</div>
            </div>
          </template>
        </van-cell>

        <van-button v-if="currentOrder.billstatus == 0" block type="danger" style="margin-top: 16px"
          @click="handleDelete(currentOrder.orderno)">
          删除订单
        </van-button>
      </van-cell-group>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { showConfirmDialog, showToast } from 'vant'
import service from '@/api'
import dayjs from 'dayjs'
import { useRoute, useRouter } from 'vue-router'

const searchForm = ref({
  orderNo: '',
  billDateRange: '', // 初始化为空数组
  statusText: ''
})

const statusMap = {
  0: '开立态',
  1: '审批中',
  2: '审批通过',
  3: '审批不通过'
}

const statusOptions = [
  { text: '全部', value: '' },
  { text: '开立态', value: 0 },
  { text: '审批中', value: 1 },
  { text: '审批通过', value: 2 },
  { text: '审批不通过', value: 3 }
]

const statusText = computed(() => {
  const option = statusOptions.find(opt => opt.value === searchForm.value.billStatus);
  return option ? option.text : '';
})

const orderList = ref([])
const currentOrder = ref(null)
const showDetail = ref(false)
const showDateRangePicker = ref(false)
const showStatusPicker = ref(false)
const currentDateRange = ref([])
const route = useRoute()
// 用户openId
let openId = route.query.openId || '';

if (!openId) {
  let src = window.location.href;
  let index = src.indexOf("?");
  if (index > 0) {
    let dataStr = src.substring(src.indexOf("?") + 1);
    let dataArray = dataStr.split("&");

    dataArray.forEach(str => {
      let param = str.split("=");
      if (param[0] == 'openId') {
        openId = param[1];
      }
    })

  }
}
let orderNoSend = '';
if (!orderNoSend) {
  let src = window.location.href;
  let index = src.indexOf("?");
  if (index > 0) {
    let dataStr = src.substring(src.indexOf("?") + 1);
    let dataArray = dataStr.split("&");

    dataArray.forEach(str => {
      let param = str.split("=");
      if (param[0] == 'orderNo') {
        orderNoSend = param[1];
      }
    })

  }
}

if (orderNoSend) {
  service.queryOrders({
    itype: "saleorder_query",//订单查询
    info: {
      orderNo: orderNoSend,
      billDateRange: '2010/01/01 - 2099/12/31',
      openId: openId
    }
  }).then((res) => {
    //debugger
    if (res.status == 'success') {
      orderList.value = res.data
    } else {
      showToast(res.message)
    }
  })
}

// 订单查询处理（带状态码判断）
const handleSearch = async () => {
  // 调用查询接口
  const res = service.queryOrders({
    itype: "saleorder_query",//订单查询
    info: {
      orderNo: searchForm._rawValue.orderNo,
      billDateRange: searchForm._rawValue.billDateRange,
      statusText: searchForm._rawValue.statusText,
      openId: openId
    }
  }).then((res) => {
    //debugger
    if (res.status == 'success') {
      orderList.value = res.data
    } else {
      showToast(res.message)
    }
  })

}

const loadpdf = async (filepk, filename) => {
  if (!filename) {
    showToast('还未生成pdf报告');
  } else {

    // 1. PDF文件URL（可以是后端API或静态文件路径）
    const pdfUrl = 'http://api.accrlab.com/qdxt/sendnc/dobusinessget?filepk=' + filepk;
    //alert (pdfUrl);
    // 2. 创建隐藏的<a>标签触发下载
    const link = document.createElement('a');
    link.href = pdfUrl;
    link.target = '_blank';
    //link.download = '检验报告.pdf'; // 设置下载文件名
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

  }
}

// 删除订单二次确认流程
const handleDelete = async (orderno) => {
  try {
    await showConfirmDialog({
      title: '确认删除',
      message: '确定要删除该订单吗？'
    })
    // 调用删除
    const res = service.deleteOrder({
      itype: "saleorder_delete",//订单查询
      info: {
        orderNo: orderno,
        openId: openId
      }
    }).then((res) => {
      //debugger
      if (res.status == 'success') {
        showToast('删除成功');
        showDetail.value = false;
        //debugger
        const res = service.queryOrders({
          itype: "saleorder_query",//订单查询
          info: {
            orderNo: searchForm._rawValue.orderNo,
            billDateRange: searchForm._rawValue.billDateRange,
            statusText: searchForm._rawValue.statusText,
            openId: openId
          }
        }).then((res) => {
          //debugger
          if (res.status == 'success') {
            orderList.value = res.data
          } else {
            showToast(res.message)
          }
        })

      } else {
        showToast(res.message)
      }
    })

  } catch (error) {
    showToast('已取消')
  }
}

const confirmDateRange = (values) => {
  if (values) {
    searchForm.value.billDateRange = values.map(date => dayjs(date).format('YYYY/MM/DD')).join(' - ')
  }
  showDateRangePicker.value = false
}

const confirmStatus = ({ selectedOptions }) => {
  searchForm.value.statusText = selectedOptions[0].value
  showStatusPicker.value = false
}

const showOrderDetail = (order) => {
  //debugger
  currentOrder.value = order
  showDetail.value = true
}
</script>

<style scoped>
.product-item {
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}
</style>